package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/*
    全局通用异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R method1(SQLIntegrityConstraintViolationException ex){
        //处理：{code:0,msg: "tom已存在"}
        //System.out.println(ex.getMessage());//Duplicate entry 'tom' for key 'idx_username'
        if(ex.getMessage().contains("Duplicate entry")){
            //就是用户名重复这个问题
            String[] strs = ex.getMessage().split(" ");
            return R.error(strs[2]+"已存在");
        }

        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R method2(CustomException ex){
        return R.error(ex.getMessage());
    }
}
